#include "Stack.h"
#include "UI.h"
#include "RS232.h"

#include <stdlib.h>

void
stack_initialize(Stack *stack)
{
  stack->Next = 0;

  // iterate through Stack of Cards
  unsigned int i;
  for (i = 0; i < STACK_MAX_CARDS; i++)
    // and initialize cards
    stack->Cards[i] = (i % 52) + 1;
}

void
stack_shuffle(Stack *stack, unsigned int times)
{
  stack->Next = 0;
  ui_shuffling(0, 0);
  rs232_shuffling();

  unsigned int i, card;
  for (i = 0; i < times; i++) {
    for (card = 0; card < STACK_MAX_CARDS; card++) {
      unsigned int j = random() % STACK_MAX_CARDS;

      Card tmp = stack->Cards[card];
      stack->Cards[card] = stack->Cards[j];
      stack->Cards[j] = tmp;

      if (!(card % 10)) {
        unsigned int percent =
            ((i * 100) / times) + ((card * 100) / (STACK_MAX_CARDS * times));
        ui_shuffling_update(tmp, percent);
      }
    }
  }
}

Card
stack_next_card(Stack *stack)
{
  if (stack->Next >= STACK_MAX_CARDS)
    return 0;

  Card next = stack->Cards[stack->Next];
  stack->Next++;
  return next;
}

unsigned int
stack_remaining_cards(Stack *stack)
{
  return (STACK_MAX_CARDS - stack->Next);
}
